package app.caihan.scframe.base.activity

import android.content.res.Resources
import android.os.Build
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import app.caihan.scframe.R
import app.caihan.scframe.util.PermissionHelper
import app.caihan.scframe.util.StatusBarConfig
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.customview.getCustomView
import com.afollestad.materialdialogs.lifecycle.lifecycleOwner
import com.blankj.utilcode.util.*
import org.jetbrains.anko.contentView

/**
 * activity基类
 * 实现了:
 * 1.屏幕适配方案
 * 2.状态栏字体切换
 * 3.根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘
 * 4.动态权限
 *
 * @author Seven-C
 * @date 2020/7/27
 */
abstract class BaseActivity : AppCompatActivity(), IBaseActivity {

    protected val simpleActivityTag = javaClass.simpleName

    private val isUseAutoSize by lazy { useAutoSizeCompat() }

    private var statusBarConfig: StatusBarConfig? = null

    private val progressDialog by lazy {
        MaterialDialog(this)
            .cancelable(false)
            .cornerRadius(8f)
            .customView(R.layout.scframe_progress_dialog_view, noVerticalPadding = true)
            .lifecycleOwner(this)
            .maxWidth(R.dimen.dialog_width)
    }


    /**
     * 是否需要使用屏幕适配方案
     */
    private fun useAutoSizeCompat(): Boolean {
        return false
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(savedInstanceState)
    }

    open fun setContentView(savedInstanceState: Bundle?) {
        super.setContentView(bindLayoutId())
    }

    //*根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘 start *//
    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            val v = currentFocus
            if (isShouldHideKeyboard(v, ev)) {
                //关闭软键盘
                KeyboardUtils.hideSoftInput(this)
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    /**
     * 如果焦点不是EditText则忽略
     */
    private fun isShouldHideKeyboard(v: View?, event: MotionEvent): Boolean {
        if (v != null && v is EditText) {
            val l = intArrayOf(0, 0)
            v.getLocationInWindow(l)
            val left = l[0]
            val top = l[1]
            val bottom = top + v.height
            val right = left + v.width
            return !(event.x > left && event.x < right
                    && event.y > top && event.y < bottom)
        }
        return false
    }
    //*根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘 end *//


    //*动态权限请求 start*//

    fun openAppSettings() {
        PermissionUtils.launchAppDetailsSettings()
    }

    fun isGranted(vararg permissions: String): Boolean {
        return PermissionUtils.isGranted(*permissions)
    }

    private fun requestPermissionAddWarningMsg(
        callback: PermissionUtils.SimpleCallback,
        snackbarStr: String,
        vararg permissions: String
    ) {
        PermissionHelper.request(this, callback, snackbarStr, *permissions)
    }

    fun requestPermission(callback: PermissionUtils.SimpleCallback, vararg permissions: String) {
        requestPermissionAddWarningMsg(callback, "", *permissions)
    }

    //是否允许修改系统设置
    private fun requestWriteSettings() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            PermissionUtils.requestWriteSettings(object : PermissionUtils.SimpleCallback {
                override fun onGranted() {
                }

                override fun onDenied() {
                }
            })
        }
    }

    //允许显示在其他应用上层
    private fun requestDrawOverlays() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            PermissionUtils.requestDrawOverlays(object : PermissionUtils.SimpleCallback {
                override fun onGranted() {
                }

                override fun onDenied() {
                }
            })
        }
    }

    //*动态权限请求 end*//


    /**
     * blankj大神的屏幕适配方案
     */
    override fun getResources(): Resources? {
        return if (isUseAutoSize) {
            if (ScreenUtils.isPortrait()) {
                AdaptScreenUtils.adaptWidth(super.getResources(), 750)
            } else {
                AdaptScreenUtils.adaptHeight(super.getResources(), 750)
            }
        } else {
            super.getResources()
        }
    }

    /**
     * 默认是会开启沉浸式模式,如果是
     */
    protected open fun getStatusBarConfig(): StatusBarConfig? {
        return StatusBarConfig()
    }

    /**
     * 框架默认使用白色导航栏,黑色导航栏字体,并且会对根布局进行一个MarginTop的操作
     */
    protected open fun setStatusBarStyle() {
        contentView?.post {
            if (statusBarConfig == null) statusBarConfig = getStatusBarConfig()
            statusBarConfig?.let {
                //isLightMode true=状态栏黑色字体,false=状态栏白色字体(系统默认)
                val isLightMode = BarUtils.isStatusBarLightMode(this)
                if (isLightMode != it.isDarkFont) {
                    BarUtils.setStatusBarLightMode(this, it.isDarkFont)
                }
                BarUtils.setStatusBarColor(this, ColorUtils.getColor(it.statusBarColor))
                BarUtils.addMarginTopEqualStatusBarHeight(this.contentView!!)
            }
        }
    }

    /**
     * 打开等待框
     */
    protected fun showProgressDialog(message: String = "") {
        if (!progressDialog.isShowing) {
            if (message.isNotEmpty()) {
                progressDialog.getCustomView().run {
                    this.findViewById<TextView>(R.id.tvTip).text = message
                }
            }
            progressDialog.show()
        }

    }

    /**
     * 关闭等待框
     */
    protected fun dismissProgressDialog() {
        if (progressDialog.isShowing) progressDialog.dismiss()
    }
}